<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="always">
        <!-- 头部 -->
        <div slot="header">
          <span>{{ testQuestionsEnter }}</span>
        </div>
        <!-- 主体 -->
        <el-form label-width="120px" :model="form" ref="form" :rules="rules">
          <!-- 学科  -->
          <!-- 展示在页面的是label的值 打印的是value的值 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.subjectID"
              @change="subjectFn"
            >
              <el-option
                v-for="(item, index) in subjectList"
                :key="index"
                :value="item.value"
                :label="item.label"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <!-- 展示在页面的是label的值 打印的是value的值 -->

          <el-form-item label="目录：" prop="catalogID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.catalogID"
            >
              <el-option
                v-for="(item, index) in directorysimpleList"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.enterpriseID"
            >
              <el-option
                v-for="(item, index) in companysList"
                :key="index"
                :label="item.company"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市：" prop="province">
            <el-select
              placeholder="请选择"
              style="width: 198px"
              v-model="form.province"
              :value="form.province"
              @change="provincesFn"
            >
              <el-option
                v-for="(item, index) in provincesList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <el-select
              placeholder="请选择"
              style="width: 198px; margin-left: 4px"
              v-model="form.city"
            >
              <el-option
                :value="item"
                v-for="(item, index) in citysList"
                :key="index"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              placeholder="请选择"
              style="width: 400px"
              v-model="form.direction"
            >
              <el-option
                :label="item"
                :value="item"
                v-for="item in directionList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型：" prop="questionType">
            <el-radio-group v-model="form.questionType" @change="RadioChangeFn">
              <el-radio label="1">单选</el-radio>
              <el-radio label="2">多选</el-radio>
              <el-radio label="3">简答</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio-group v-model="form.difficulty">
              <el-radio label="1">简单</el-radio>
              <el-radio label="2">一般</el-radio>
              <el-radio label="3">困难</el-radio>
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干：" prop="question">
            <quill-editor
              @blur="$refs.form.validateField('question')"
              v-model="form.question"
              :options="editorOption"
              ref="myQuillEditor"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item label="选项：" v-show="form.questionType !== '3'">
            <el-form-item
             v-model="form.options"
              v-for="(item, index) in form.zimu"
              :key="index"
              style="padding-bottom: 20px"
            >
              <!-- radio 通过 1 2 3 判断是 单选 多选 还是 简答 -->
              <el-radio
                :label="index"
                v-show="form.questionType === '1'"
                style="margin-right: 0px"
                v-model="form.radioA"
                >{{ item.code }}：</el-radio
              >
              <el-checkbox
                v-show="form.questionType === '2'"
                v-model="form.zimu[index].isRight"
                :label="index"
                style="margin-right: 0px"
                >{{ item.code }}：</el-checkbox
              >
              <el-input style="width: 240px" v-model="item.title"></el-input>
              <el-upload
                v-model="form.upload"
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <span>上传图片</span>
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <i v-else class="el-icon-circle-close"></i>
              </el-upload>
            </el-form-item>
            <!-- 增加选项与答案 -->
            <el-button
              type="danger"
              :disabled="form.questionType !== '2'"
              v-model="form.addOption"
              size="small"
              @click="AddAnswer"
              >+增加选项与答案</el-button
            >
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频：">
            <el-input style="width: 400px" v-model="form.videoURL"></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析：" prop="answer">
            <quill-editor
              @blur="$refs.form.validateField('answer')"
              v-model="form.answer"
              ref="myQuillEditor"
              :options="editorOption"
            >
            </quill-editor>
            <!-- <div v-html="this.announcementDetail"></div> -->
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注：">
            <el-input
              :rows="4"
              type="textarea"
              style="width: 400px"
              v-model="form.remarks"
            ></el-input>
          </el-form-item>
          <!-- 试题标签  -->
          <el-form-item label="试题标签：">
            <el-select
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
              v-model="form.tags"
              style="width: 400px"
            >
              <el-option
                v-for="(item, index) in tagsList"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <!-- 确认提交 -->
          <el-form-item>
            <el-button :type="ButtonColor" @click="preSentFn">{{form.SureSubmit}}</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// require styles
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { Message } from 'element-ui'
import { quillEditor } from 'vue-quill-editor'
// 学科
import { simple as getSubject } from '@/api/hmmm/subjects'
// 基础题库添加  详情 修改
// , update as UpdateDirectory
import {
  add as getMoreDirectory,
  detail as getDirectoryDetail,
  update as UpdateDirectory
} from '@/api/hmmm/questions'
// 目录
import { simple as getdirectorysimpleList } from '@/api/hmmm/directorys'
// 企业
import { list as getCompanysList } from '@/api/hmmm/companys'
// 城市和区域
import {
  provinces as getProvincesList,
  citys as getCitysList
} from '@/api/hmmm/citys'
// 方向
import { direction as getDirection } from '@/api/hmmm/constants'
// 标签
import { simple as getTagesList } from '@/api/hmmm/tags'

export default {
  components: {
    quillEditor
  },
  data () {
    return {
      test: false,
      testQuestionsEnter: '试题录入',
      id: '',
      // 单选 多选框的 默认值
      isShow: true,
      IsDisabled: 'false',
      editorOption: {
        modules: {
          // theme: 'snow',
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ list: 'ordered' }, { list: 'bullet' }], // 列表
            ['blockquote'], // 引用
            ['code-block', 'image', 'link'] // 代码块 上传图片 上传视频
          ]
        }
      },
      zimuMore: 69,
      form: {
        id: '',
        options: [],
        SureSubmit: '确认提交',
        zimu: [
          { code: 'A', title: '', img: '', isRight: false },
          { code: 'B', title: '', img: '', isRight: false },
          { code: 'C', title: '', img: '', isRight: false },
          { code: 'D', title: '', img: '', isRight: false }
        ],

        upload: '',
        Ischecked: [],
        answer: '',
        question: '',
        videoURL: '',
        remarks: '',
        subjectID: '',
        direction: '',
        enterpriseID: '',
        questionType: '1',
        radioChange: 1,
        difficulty: '1',
        province: '',
        city: '',
        catalogID: '',
        radioA: '',
        tags: [],
        addOption: '',
        radioBB: ''
      },
      subjectList: [],
      directorysimpleList: [],
      // 方向
      directionList: getDirection,
      companysList: [],
      // 城市
      provincesList: getProvincesList(),
      citysList: [],
      imageUrl: '',
      listList: [],
      tagsList: [],
      rules: {
        subjectID: [
          {
            required: true,
            message: '请选择学科',
            trigger: 'change'
          }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [{ required: true, message: '请选择企业', trigger: 'change' }],
        province: [{ required: true, message: '请选择地区', trigger: 'change' }],
        direction: [{ required: true, message: '请选择方向', trigger: 'change' }],
        questionType: [{ required: true, message: '' }],
        difficulty: [{ required: true, message: '' }],
        question: [{ required: true, message: '请输入题干', trigger: ['blur', 'change'] }],
        answer: [{ required: true, message: '请输入题干', trigger: ['blur', 'change'] }]
      }
    }
  },
  // 初始化的数据
  async created () {
    this.ButtonColor = 'primary'
    const res = await getSubject(this.form)
    // console.log(res.data)
    // 学科
    this.subjectList = res.data
    // console.log(this.subjectList)
    // 企业
    const res2 = await getCompanysList()
    // console.log(res2.data)
    this.companysList = res2.data.items
    await this.ChangeQuestions()
  },
  methods: {
    // 多选增加选项和答案
    AddAnswer () {
      // 多选增加选项和答案
      this.form.zimu.push({
        code: String.fromCharCode(this.zimuMore),
        title: '',
        img: '',
        isRight: false
      })
      // console.log(this.form.zimu)
      this.zimuMore++
    },
    // 单选 多选 简答 的判断
    RadioChangeFn (value) {
      // console.log(value)
      if (value === '1') {
        // 默认展示 选项
        this.isShow = true
        // 值为1  禁用 增加按钮
        this.form.radioChange = 1
        // 是单选 就让 多选的值为空
        this.form.Ischecked = []
      } else if (value === '2') {
        // 默认展示 选项
        this.isShow = true
        // 值为2  可用 增加按钮
        this.form.radioChange = 2
        // 是多选 就让 单选的值为空
        this.form.radioA = ''
      } else if (value === '3') {
        // 不展示 选项
        this.isShow = false
      }
    },

    // 标签  // 目录
    async subjectFn (e) {
      // console.log(e)
      // 目录
      const res = await getdirectorysimpleList({
        subjectID: this.form.subjectID
      })
      console.log(res.data)
      this.directorysimpleList = res.data
      this.form.catalogID = ''
      // 标签
      const res1 = await getTagesList({ subjectID: this.form.subjectID })
      console.log(res1.data)
      this.tagsList = res1.data
      this.form.tags = ''
    },
    // 区域
    async provincesFn (e) {
      // console.log(e)
      const res = await getCitysList(e)
      this.citysList = res
      this.form.city = ''
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 校验表单
    async preSentFn () {
      // console.log(this.form.company)
      // 如果有id 证明是修改试题
      await this.$refs.form.validate()
      if (this.$route.query.id) {
        await UpdateDirectory({
          id: this.form.id,
          subjectID: this.form.subjectID, // 学科
          catalogID: this.form.catalogID, // 目录
          enterpriseID: this.form.enterpriseID, // 企业
          province: this.form.province, // 城市
          city: this.form.city, // 地区
          direction: this.form.direction, // 方向
          questionType: this.form.questionType, // 题型
          difficulty: this.form.difficulty, // 难度
          question: this.form.question, // 题干
          options: this.form.options, // 选项
          videoURL: this.form.videoURL, // 解析视频
          answer: this.form.answer, // 答案解析
          remarks: this.form.remarks, // 题目备注
          tags: this.form.tags.join(',')// 试题标签
        })
        // console.log(res)
        Message.success('修改成功')
        this.$router.push({ path: '/questions/list' })
      } else {
        // 没有id 是添加试题
        await getMoreDirectory({
          subjectID: this.form.subjectID, // 学科
          catalogID: this.form.catalogID, // 目录
          enterpriseID: this.form.enterpriseID, // 企业
          province: this.form.province, // 城市
          city: this.form.city, // 地区
          direction: this.form.direction, // 方向
          questionType: this.form.questionType, // 题型
          difficulty: this.form.difficulty, // 难度
          question: this.form.question, // 题干
          options: this.form.zimu, // 选项
          videoURL: this.form.videoURL, // 解析视频
          answer: this.form.answer, // 答案解析
          remarks: this.form.remarks, // 题目备注
          tags: this.form.tags.join(',')// 试题标签
        })
        Message.success('提交成功')
        this.$router.push({ path: '/questions/list' })
      }
    },
    // 数据回显
    async ChangeQuestions () {
      if (this.$route.query.id) {
        const res = await getDirectoryDetail({ id: this.$route.query.id })
        console.log(res.data)
        this.form.id = res.data.id
        // 回显后的数据
        this.form = res.data
        // 把学科id传过去
        this.form.subjectID = res.data.subjectID
        const res2 = await getdirectorysimpleList({
          subjectID: this.form.subjectID
        })
        // 再遍历目录
        // console.log(res2.data)
        this.directorysimpleList = res2.data
        // 目录
        this.form.catalogID = res.data.catalogID
        // 标签
        const res1 = await getTagesList({ subjectID: this.form.subjectID })
        this.tagsList = res1.data
        this.form.tags = res.data.tags.split(',')
        // 选项
        this.form.zimu = res.data.options
        if (res.data.questionType === '1') {
          this.isShow = true
          this.form.radioChange = 1
        } if (res.data.questionType === '2') {
          console.log(res.data)
          this.form.zimu = res.data.options
          this.form.zimu.forEach(item => {
            if (item.isRight === 1) item.isRight = true
          })
          this.isShow = true
          this.form.radioChange = 2
          // if (res.data.options[index] === 1) {
          //   this.test = true
          // }
        } else {
          this.isShow = false
        }
        this.testQuestionsEnter = '试题修改'
        this.form.SureSubmit = '确认修改'
        this.ButtonColor = 'success'
      }
    }
  }
}
</script>

<style scoped lang="scss">
.quill-editor {
  ::v-deep .ql-editor {
    height: 200px;
  }
}
.avatar-uploader {
  display: inline-block;
  margin-left: 4px;
  vertical-align: middle;
}
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  width: 100px;
  height: 60px;
  line-height: 60px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader i {
  position: absolute;
  right: 0;
  top: 0;
  -webkit-transform: translate(50%, -50%);
  transform: translate(50%, -50%);
  background: #fff;
  font-size: 18px;
  color: #999;
}
.avatar {
  width: 100px;
  height: 60px;
  display: block;
}

::v-deep .el-tag.el-tag--info {
  color: rgb(34, 32, 33);
  background: linear-gradient(to left, #e7f27f, rgb(199, 237, 12), #fff222);
}
::v-deep .el-select-dropdown__item.hover,
.el-select-dropdown__item:hover {
  background-color: #fff222;
}
</style>
